/*
AlliedBridge Content Management System
Copyright (C) 2006 AlliedBridge

This program is free software; you can redistribute it and/or modify it under the
terms of the GNU General Public License as published by the Free Software Foundation;

This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied
warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.

You should have received a copy of the GNU General Public License along with this program; if not, write to the
Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
package org.volume4.authentication.reminders;

import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.*;
import java.util.Properties;


/** Class used to send a user, to his/her email address, his username and 
 password, based on a database lookup, when a email address match is made.*/
public class PasswordReminder extends HttpServlet {
    
    public String app_root, email, username, userid, password, message, messageFail, messageSuccess, DRIVER, URL, USER, PASS;
    
    public void init() throws ServletException {
        ServletContext context = getServletContext();
        DRIVER = context.getInitParameter("driver");
        URL = context.getInitParameter("mc_dburl");
        USER = context.getInitParameter("mc_dbuser");
        PASS = context.getInitParameter("mc_dbpass");
    }
    
    /** Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        
        response.setContentType("text/html");
        PrintWriter out = response.getWriter();
        Connection con = null;
        messageFail = "No user found. A user with the email address" + request.getParameter("email") + "could not be found. Please check your address and try again.";
        messageSuccess = "User details sent to the specified email address.";
        
        if(request.getParameter("send") != null) {
            email = request.getParameter("email");
            
            try {
                Class.forName(DRIVER);
                con = DriverManager.getConnection(URL,USER,PASS);
                Statement stmt = con.createStatement();
                
                ResultSet rs = stmt.executeQuery("SELECT * FROM ab_users" +
                " WHERE email = '" +
                request.getParameter("email") + "'");
                
                boolean foundUser = false;
                while(rs.next()) {
                	foundUser = true;
                	
                	userid = rs.getString(1); 
                    username = rs.getString(2);                	
                    password = rs.getString(3);
                    
                    Properties props = new Properties();
                    props.put("mail.smtp.host", "mail.alliedbridge.com");
                    Session mailSession = Session.getDefaultInstance(props, null);
                    Message body = new MimeMessage(mailSession);
                    
                    InternetAddress fromUser = new InternetAddress("info@alliedbridge.com");
                    InternetAddress toUser = new InternetAddress(email);
                    
                    message =
                    "<b>AlliedBridge.com Password.Reminder</b>" +
                    "<br>Below please find your username and password." +
                    "<p>" +
                    "Username: " + username +
                    "bar />User ID: " + userid +
                    "<br />Password: " + password +
                    "</p>" +
                    "The AlliedBridge.com Team" +
                    "<br>www.alliedbridge.com" +
                    "<br>support:" +
                    "<a href=\"mailto:support@alliedbridge.com\">support@alliedbridge.com</a>";
                    
                    body.setFrom(fromUser);
                    body.setRecipient(Message.RecipientType.TO, toUser);
                    body.setSubject("Password Reminder Service from AlliedBridge");
                    body.setContent(message, "text/html");
                    
                    body.saveChanges();
                    
                    Transport transport = mailSession.getTransport("smtp");
                    transport.connect();
                    transport.send(body);
                    
                    app_root = request.getContextPath();
                    response.sendRedirect(app_root + "authentication/operation_result.jsp?message=" + messageSuccess);
                }
                
                if(foundUser == false) {
                	response.sendRedirect(app_root + "authentication/operation_result.jsp?message=" + messageFail);                	
                }
                
            } catch (AddressException ae) {
                System.out.println("Exception in Address");
                
                System.out.println(ae.getMessage());
                
            } catch(MessagingException me) {
                PrintWriter error = response.getWriter();
                error.println("Message not sent. Make sure you are connected to the internet." +
                "If you are still having trouble please mail our tech support:" +
                "<a href=\"mailto:developers@volume4.co.za?Subject=Support for Hr4Change\">support</a>");
                System.out.println("Message not Sent");
                
                
                throw new IOException(me.getMessage());
                
            } catch (Exception e) {
                e.printStackTrace();
            }
            
            finally {
                if (con != null) {
                    try {
                        con.close();
                    }
                    catch (SQLException ignore) {}
                }
            }
            
            
        }
    }
    /** Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        processRequest(request, response);
    }
    
    /** Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        processRequest(request, response);
    }
}